<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Admin\Model;

use Admin\Logic\NestedSets;

class GoodsCategoryModel extends \Think\Model
{

    protected $patchValidate = true; //开启批量验证
    /**
     * name 必填，不能重复
     * status 可选值0-1
     * sort 必须是数字
     * @var type
     */
    protected $_validate = [
        ['name', 'require', '商品分类名称不能为空'],
    ];


    /**
     * 获取所有的商品分类。
     * @return array
     */
    public function getList()
    {
        return $this->where(['status' => ['egt', 0]])->order('lft')->select();
    }

    public function addCategory()
    {
        unset($this->data[$this->getPk()]);
        $orm = D('MySQL', 'Logic');
        $nestedSets = new NestedSets($orm, $this->trueTableName, 'lft', 'rght', 'parent_id', 'id', 'level');
        return $nestedSets->insert($this->data['parent_id'], $this->data, 'bottom');
    }

    public function saveCategory()
    {
        $parent_id = $this->getFieldById($this->data['id'], 'parent_id');
        /*var_dump($parent_id);
        exit;*/
        if ($this->data['parent_id'] != $parent_id) {
            $orm = D('MySQL', 'Logic');
            $nestedSets = new NestedSets($orm, $this->trueTableName, 'lft', 'rght', 'parent_id', 'id', 'level');

            if ($nestedSets->moveUnder($this->data['id'], $this->data['parent_id'], 'bottom') === false) {
                $this->error = "无法移动到后代分类中";
                return false;
            }
        }
        return $this->save();
    }

    public function deleteCategory($id)
    {
        $orm = D('MySQL', 'Logic');
        $nestedSets = new NestedSets($orm, $this->trueTableName, 'lft', 'rght', 'parent_id', 'id', 'level');
        return $nestedSets->delete($id);
    }

}
